<template>
  <div class='main-container'>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>人员管理</el-breadcrumb-item>
      <el-breadcrumb-item>职员管理</el-breadcrumb-item>
    </el-breadcrumb>
<!-- 卡片 -->
<el-card class="box-card">
  <el-row :gutter="30">
    <el-col :span="4">
      <el-button type="primary" @click="dialogVisible=true">
        添加入职人员
      </el-button>
    </el-col>
</el-row>
  <el-table :data="userList" style="width: 100%" border stripe>
    <el-table-column prop="workNumber" label="工号"></el-table-column>
    <el-table-column prop="name" label="姓名"></el-table-column>
    <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="department" label="部门"></el-table-column>
      <el-table-column prop="post" label="岗位"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag
            :type="getStatus(scope.row.status).color"
            disable-transitions>{{getStatus(scope.row.status).text}}</el-tag>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
</el-card>
<!-- 添加待入职用户 -->
<el-dialog
  title="添加待入职用户"
  :visible.sync="dialogVisible"
  width="50%"
  @close="addClose"
 >
  <el-row>
    添加新员工信息,同时会自动给此员工提供一份合同,新员工登录系统时可见
  </el-row>
  <el-form  label-width="70px" :model="addForm" :rules="addFormRules" ref="addForm">
    <el-form-item label="工号" prop="workNumber" :disabled="true">
      <el-input v-model="addForm.workNumber"></el-input>
    </el-form-item>
    <el-form-item label="姓名" prop="name">
    <el-input v-model="addForm.name"></el-input>
  </el-form-item>
   <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
   <el-form-item label="部门" prop="department">
     <el-select v-model="addForm.department" placeholder="请选择">
       <el-option
         v-for="item in selectOptions"
         :key="item"
         :label="item"
         :value="item">
       </el-option>
     </el-select>
  </el-form-item>
    <el-form-item label="岗位" prop="post">
      <el-input v-model="addForm.post"></el-input>
    </el-form-item>

</el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>
<script>
import login from '../Login'

export default {
  data() {
    //验证邮箱规则
    const emailCheck = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确邮箱'))
    }
    //验证手机规则
    const mobileCheck = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0-9]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确手机'))
    }
    return {
      queryInfo:{
        query:'',
        pagenum:1,
        pagesize:2,

      },
      userList:[],
      total:0,
      dialogVisible:false,
      edit_dialogVisible:false,
      setDialogVisible:false,
      editForm:{},
      userInfo:{},
      rolesList:[],
      selectedRole:'',
      addForm:{
        workNumber:'',
        name:'',
        email: '',
        post: '',
        department:'',
      },
      addFormRules:{
        name:[{
          required:true,message:"请输入姓名",trigger:"blur"
      },{
        max:10,min:2,message:"长度在2到10之间"
      }],
        department:[{
          required:true,message:"请选择部门",trigger:"blur"
        }],
        post:[{
          required:true,message:"请填写岗位",trigger:"blur"
        }],
      email:[{
          required:true,message:"请输入邮箱",trigger:"blur"
      },{
        validator:emailCheck,
        trigger:'blur'
      }]
      },
      selectOptions:[
        '研发部',
        '产品部',
        '设计部',
        '运营部',
        '市场部',
        '人力部',
        '行政部',
      ],
      editFormRules:{
        email:[
          {
            required:true,message:"请输入邮箱",trigger:"blur"
          },{
          validator:emailCheck,
          trigger:'blur'
        }
        ],
        mobile:[
          {
            required:true,message:"请输入手机",trigger:"blur"
          },{
            validator:mobileCheck,
            trigger:'blur'
          }
        ],
      },
    }
  },
  watch:{
    dialogVisible:{
      handler(val){
        this.total=this.userList.length
        this.addForm.workNumber=10001+this.total
        console.log(this.addForm.workNumber)
      }
    }
  },
  created(){
    this.getUserList()
  },
  computed: {

  },
  methods:{
    getStatus(val){
        let statusMap = {
          '0':{color:'warning',text:'待入职'},
          '1':{color:'primary',text:'已入职'},
          '2':{color:'danger',text:'待离职'},
          '3':{color:'info',text:'已离职'}
        }
        return statusMap[val]
    },
    getUserList:async function(){
      // const{data:res} =await this.$http.get('users',{params:this.queryInfo})
      const{data:res} =await this.$http.get('/user/getUserList')
      console.log(res)
      this.userList=res.data
    },
    // 获取最新的pagesize
    handleSizeChange:function(newsize){
        this.queryInfo.pagesize=newsize
        this.getUserList()
    },
    handleCurrentChange:function(newPage){
      this.queryInfo.pagenum=newPage
      this.getUserList()
    },
    userStateChange:async function(userInfo){
      console.log(userInfo)
      const {data:res}=await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_status}`)
      if(res.meta.status!==200){
        userInfo.mg_status=!userInfo.mg_status
        return this.$message.error("更新用户失败")
      }
      this.$message.success("更新成功")
    },
    // 对话框关闭事件
    addClose:function(){
      this.$refs.addForm.resetFields();
    },
    editClose:function(){
      this.$refs.editForm.resetFields();
    }
    ,
    addUser: function(){
      this.$refs.addForm.validate(async valid=>{
        if(!valid){
          return
        }
        const {data:res}=await this.$http.post('/user/register',this.addForm)
        if(res.code!==0){
          this.$message.error("添加失败");
        }
         this.$message.success(res.data);
         this.dialogVisible=false;
         await this.getUserList();
      })
    },
    editUser:function(){
      this.$refs.editForm.validate(async valid=>{
        if(!valid){
          return
        }
         const {data:res}=await this.$http.put('users/'+this.editForm.id,{email:this.editForm.email,mobile:this.editForm.mobile})
        if(res.meta.status!==200){
          this.$message.error("修改失败");
        }
         this.$message.success("修改成功");
         this.edit_dialogVisible=false;
         this.getUserList();
      })
    },
    showEditDialog:async function(id){

      const {data:res}=await this.$http.get("users/"+id)
      if(res.meta.status!==200){
        return this.$message.error("查询失败")
      }
      this.editForm=res.data
      this.edit_dialogVisible=true;
    },
    removeById:async function(id){
      // 弹出弹框
      const confirmResult= await this.$confirm('此操作将永久删除该用户, 确认吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).catch(err=>err);
      if(confirmResult!=='confirm'){
        return this.$message.info("已取消")
      }
      const {data:res}= await this.$http.get(`admin/deleteUserById/${id}`)
      if(res.meta.status!==200){
        return this.$message.error("删除失败")
      }
      this.$message.success("删除成功")
      await this.getUserList();
    },
    // 展示分配权限对话框
    showSetDialog:async function(role){
      this.userInfo=role
      console.log(role,"role")
      const {data:res}=await this.$http.get('admin/findAllRole')
      // console.log(res)
      if(res.data.status!==200){
          return this.$message.error("获取角色失败")
        }
      this.rolesList=res.meta
      // this.getLeafKeys(role,this.defKeys);
      this.uId=role.uid
      this.setDialogVisible=true
    },
    searchUser: async  function(){
      const {data:res}=await this.$http.get(`admin/findAllUser/${this.queryInfo.query}`)
      if(res.data.status!==200){
        return this.$message.error("查找失败")
      }
      this.userList=[res.meta]
      this.userList.role=res.meta.length!==0?res.meta.roles[0].role:"普通用户"
      this.$message.success("查找成功")

    },
    saveRoleInfo:async function(){
      if(!this.selectedRole){
        return this.$message.error("请选择角色!")
      }
      const {data:res}=await this.$http.post(`admin/userAddRole?role=${this.selectedRole}&uid=${this.uId}`)
        // console.log(res.meta)
      if(res.data.status!==200){
        return this.$message.error("更新失败")
      }

      this.$message.success("更新成功")
      await this.getUserList()
      this.setDialogVisible=false
    },
    setRoleClosed:function(){
      this.selectedRole=''
      this.userInfo={}
    }
  }
}
</script>
<style lang="less" scoped>
  .main-container{
    padding: 10px 20px;
    h4{
      color: gray;
      font-size:20px;
      font-weight: normal
    }
  }
</style>
